import express from 'express'
import { Request, Response, NextFunction } from 'express'
import registerPlugin from '../plugin/plugin'
import { typeRegisterPlugin } from '../plugin/plugin'
import logger from '../tools/logger'

interface typeDefaultRouterList {
    url: string,
    method:'ALL' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD',
    run: (registerPlugin: typeRegisterPlugin<any>, req: Request, res: Response, next?: NextFunction) => void;
}

const router = express.Router()
const defaultRouterList: typeDefaultRouterList[] = []
const registerRouter = (routers: typeDefaultRouterList) => {
    logger.info(`registerRouter : ${routers.url} method: ${routers.method}`)
    defaultRouterList.push(routers)
}
router.all('*', (req, res, next) => {
    defaultRouterList.map(routers => {
        if (req.path == routers.url && req.method == routers.method) {
            logger.info(`Request : ${req.url} Method: ${req.method} IP : ${req.ip}`)
            routers.run(registerPlugin, req, res, next)
        }
    })
})

export {registerRouter,typeDefaultRouterList}

export default (()=>{
    import('./registerRouter')
    return router
})()